package com.aioz.security.controller;


import com.aioz.security.common.ResponseResult;
import com.aioz.security.utils.RedisCache;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
public class CaptchaController {

    // Redis缓存对象
    @Autowired
    private RedisCache redisCache;

    @PostMapping(value = "/captcha")
    public ResponseResult captcha(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = "captcha:" + UUID.randomUUID().toString().replaceAll("\\-", "");
        // 存入redis并设置过期时间为30分钟
        redisCache.setCacheObject(key,verCode,2, TimeUnit.MINUTES);
        // 将key和base64返回给前端
        map.put("key",key);
        map.put("catpchaUrl",specCaptcha.toBase64());
        return new ResponseResult(200,map);
    }
}
